from datetime import datetime
from typing import Optional, TYPE_CHECKING

from sqlmodel import SQLModel, Field, Relationship

from app.models import SQLBaseModel
from app.models.base import IdType
from ..schemas.base_schema import DeviceType

if TYPE_CHECKING:
    from .user import User


class BaseDevice(SQLModel):
    device_fingerprint:str = Field(index=True, description="设备指纹")
    name:Optional[str]  = Field(default=None, description="设备名称")
    type:Optional[DeviceType]  = Field(default=None, index=True, description="设备类型")
    os:Optional[str]  = Field(default=None, index=True,description="操作系统及版本")
    browser:Optional[str]  = Field(default=None, index=True,description="浏览器")
    ip_address: Optional[str] = Field(default=None, description="IP地址")
    user_agent: str = Field(description="用户代理信息")

    last_login_datetime:Optional[datetime] = Field(default=None, description="最后登录时间")

    is_active:bool = Field(default=True,index=True,description="活跃设备")

    description: Optional[str]  = Field(default=None, description="描述")

    is_enabled: bool = Field(default=True, index=True, description="启用")


class Device(SQLBaseModel,BaseDevice,table=True):
    __tablename__ = "device"

    """一对多关系"""
    user_id: Optional[IdType] = Field(default=None, index=True, foreign_key="user.id", description="用户ID")
    user: Optional["User"] = Relationship(back_populates="devices")
